#!/bin/bash

# Web Notes 部署状态检查脚本
echo "🔍 Web Notes 部署状态检查"
echo "=================================="

# 检查PM2服务
echo ""
echo "📊 PM2 服务状态:"
pm2 list | grep -E "(web-notes|online|stopped)" || echo "❌ 没有找到 web-notes 服务"

# 检查端口监听
echo ""
echo "🔌 端口监听状态:"
netstat -tlnp | grep :3000 && echo "✅ 3000端口正常监听" || echo "❌ 3000端口未监听"
netstat -tlnp | grep :80 && echo "✅ 80端口正常监听" || echo "❌ 80端口未监听"

# 检查后端健康
echo ""
echo "💓 后端健康检查:"
if curl -s http://localhost:3000/health > /dev/null; then
    echo "✅ 后端直连正常"
    curl -s http://localhost:3000/health
else
    echo "❌ 后端直连失败"
fi

# 检查Nginx代理
echo ""
echo "🔄 Nginx代理检查:"
if curl -s http://localhost/api/health > /dev/null; then
    echo "✅ Nginx代理正常"
    curl -s http://localhost/api/health
else
    echo "❌ Nginx代理失败"
fi

# 检查前端文件
echo ""
echo "🌐 前端文件检查:"
if [ -f "/var/www/html/index.html" ]; then
    echo "✅ 前端文件存在"
    echo "文件大小: $(du -h /var/www/html/index.html)"
    echo "文件数量: $(find /var/www/html -type f | wc -l) 个文件"
else
    echo "❌ 前端文件不存在"
fi

# 检查Nginx配置
echo ""
echo "⚙️  Nginx配置检查:"
nginx -t && echo "✅ Nginx配置正确" || echo "❌ Nginx配置错误"

# 检查环境变量文件
echo ""
echo "🔧 环境配置检查:"
if [ -f "/var/www/web-notes/web-notes-frontend/.env.production" ]; then
    echo "✅ 生产环境配置存在:"
    cat /var/www/web-notes/web-notes-frontend/.env.production
else
    echo "❌ 生产环境配置不存在"
fi

# 显示日志位置
echo ""
echo "📝 日志文件位置:"
echo "  - PM2日志: pm2 logs web-notes-api"
echo "  - Nginx访问日志: /var/log/nginx/web-notes-access.log"
echo "  - Nginx错误日志: /var/log/nginx/web-notes-error.log"

# 测试建议
echo ""
echo "🧪 测试建议:"
echo "  1. 浏览器访问: http://$(hostname -I | awk '{print $1}')/"
echo "  2. API测试: curl http://$(hostname -I | awk '{print $1}')/api/health"
echo "  3. 检查浏览器控制台是否显示: '📡 最终 API URL: /api'"

echo ""
echo "检查完成！"